import { Form, Field } from 'mobx-react-form';
import { observable, action, computed, autorun, toJS } from 'mobx';
import * as _ from 'lodash';
import { isNumber } from '../../util/typeUtil';
import validatorjs from 'validatorjs';
import { message, Modal } from 'antd';
import window from '../../util';
import CardStore from '../card';
import { deal4ReplaceDatas } from '.';
import { WeaLocaleProvider } from 'ecCom';
import { modeForm } from '../../util/excelUtil';
import { verifyCustomRegisterEvent } from '../../util/cubeUtil';
import $ from 'jquery';
import { getDomIdByFieldKey ,guid} from '../../util/typeUtil';
import * as InputUtil from '../../components/excel-layout/cell-field/input-element/wf-form-input/util'

const getLabel = WeaLocaleProvider.getLabel;

export function checkBrowser({ field }) {
  return [!!field.values().value, _.get(rules, `${field.key}.message`)];
}

export class CubeField extends Field {
  form: CubeForm;

  constructor(props: any, form: CubeForm) {
    super(props);
    this.form = form;
    autorun(() => {
      if (this.viewAttr == 3 || (this.isMandatory && this.viewAttr == undefined)) {
        this.set('rules', 'required');
      } else {
        this.set('rules', '');
      }
    });
  }

  @observable uploadState: string = '';

  @observable valueSpan = null;
  @observable valueObj = [];

  @observable color: string;

  isInit: boolean = false;
  set: Function;
  path: string;
  key: string;
  execHook: Function;
  values: Function;
  validate: Function;
  showErrors: Function;
  map: Function;
  has: Function;
  bind: Function;
  $: Function;
  extra: {}
  value: any;
  @observable isAdd: boolean = false;
  @observable isCopy: boolean = false;
  @observable isDelete: boolean = false;
  @observable tips = { visible: false, msg: '' }

  @observable detailDefaultValue = {};
  @observable uploadData: any = {};
  @observable dataParams: any = undefined;
  @observable browserProps: any = undefined;
  @observable pageSize = 10;  //明细表分页大小
  @observable pageNum = 1;     //明细表当前页
  @observable forceRender: any = "";
  @observable startDate: any = null;  //开始时间
  @observable endDate: any = null; //结束时间

  @observable
  viewAttrs: any = {}




  @action
  setViewAttrs = (key: string, viewAttr: string) => {
    if (viewAttr == '3') {
      this.viewAttrs = { ...this.viewAttrs, [key]: 1 };
      this.set('rules', '');
    } else if (viewAttr == '1') {
      this.viewAttrs = { ...this.viewAttrs, [key]: 2 };
      this.set('rules', '');
    } else if (viewAttr == '2') {
      this.viewAttrs = { ...this.viewAttrs, [key]: 3 };
      this.set('rules', 'required');
    } else if (viewAttr == '4') {
      this.viewAttrs = { ...this.viewAttrs, [key]: 4 };
      this.set('rules', '');
    } else if (viewAttr == '5') {
      this.viewAttrs = { ...this.viewAttrs, [key]: 5 };
      this.hideOrShowTr(true);
    } else {
      this.removeViewAttrs(key);
    }
  }

  @action
  setUploadState = (state: string) => {
    this.uploadState = state;
  }

  @computed get isUpload(): boolean {
    return !this.uploadState || this.uploadState == 'false' || this.uploadState == 'uploaded';
  }

  @action
  setUploadData = (data) => {
    this.uploadData = data;
  }

  @action
  removeViewAttrs = (key: string) => {
    if (key in this.viewAttrs) {
      if (this.isMandatory) {
        this.set('rules', 'required');
      } else {
        this.set('rules', '');
      }
      if (this.viewAttrs[key] == '5') {
        this.hideOrShowTr(false);
      }
      delete this.viewAttrs[key];
      this.viewAttrs = { ...this.viewAttrs };
    }
  }

  /*****属性联动---隐藏行功能 */
  @action
  hideOrShowTr = (bool: boolean) => {
    const fieldName = getDomIdByFieldKey(this.path);
    let $tr;
    let cardId = window.location.hash.slice(window.location.hash.lastIndexOf("=") + 1).replace(/%/g, "");
    if ($(`#display-${cardId}`).length > 0) {//ecme模块
      if ($(`#display-${cardId} #${fieldName}`).length > 0) {
        $tr = $(`#display-${cardId} #${fieldName}`).closest('tr');
      } else {
        $tr = $(`#display-${cardId} #${fieldName}span`).closest('tr');
      }
    } else {
      if ($('#' + fieldName).length > 0) {
        $tr = $('#' + fieldName).closest('tr');
      } else {
        $tr = $('#' + fieldName + 'span').closest('tr');
      }
    }
    if (bool) {
      $tr.hide();
    } else {
      $tr.show();
    }
  }

  @computed get viewAttr() {
    let v: any = undefined;
    _.each(this.viewAttrs, (v1) => {
      v = v1;
    });
    return v;
  }

  @computed get isView() {
    return _.get(this.form, `card.fieldsPropsToShow.${this.key}.isview`) == '1';
  }

  @computed get isEdit() {
    return _.get(this.form, `card.fieldsPropsToShow.${this.key}.isedit`) == '1';
  }

  @computed get isMandatory() {
    return _.get(this.form, `card.fieldsPropsToShow.${this.key}.ismandatory`) == '1';
  }

  @computed get isHide() {
    return _.get(this.form, `card.fieldsPropsToShow.${this.key}.ishide`) == '1';
  }

  @computed get order() {
    return _.get(this.form, `card.refreshParams.order.${this.key}`);
  }

  /***
   * ljc-快速编辑开启的情况下才会有editstate字段，返回2编辑 3 必填，
   * 其他布局不存在，所以作为判断依据是否可以编辑
   * editstate不好辨别，增加一个isquickedit字段
   */
  @computed get isquickedit() {
    const editstate = _.get(this.form, `card.fieldsPropsToShow.${this.key}.editstate`);
    return editstate == '1' ? false : editstate;
  }
  @computed get editstate() {
    return _.get(this.form, `card.fieldsPropsToShow.${this.key}.editstate`);
  }

  onChangFuncs: Function[] = [];


  getValue = () => {
    return this.values();
  }


  @action
  setSelfValue = (...args) => {
    //ljc-加了一个参数导致这里进不来了，参数判断优化性能的，为了方便拓展，用>=
    if (args.length >= 3) {  
      //QC: #775361
      if (args[1] != undefined) {
        if (args[1].indexOf(",") >= 0) {
          args[1] = args[1].replace(/,/g, ' ');
        }
      }
      this.valueObj = args[2];
      this.valueSpan = args[1];
      let key = '';
      if (args[2] && args[2][0] && args[2][0].randomFieldId) {
        args[2].forEach(item => {
          key += item.randomFieldId + ',';
        })
      }
      if (key.endsWith(',')) key = key.substr(0, key.length - 1);
      key = key || args[0];
      this.set(`${key}`);
      this.form.card.changeModeTitle(args[1], this.path); // 触发标题自动更新
    } else {
      this.set(`${args[0]}`);
      this.form.card.changeModeTitle(args[0], this.path); // 触发标题自动更新
    }
  }

  onChangeNoTrigger(...args) {
    this.setSelfValue(...args);
  }

  quickEditOnchange=(args)=>{
    const {quickEditStore,} = this.form.card;
    const editValues = quickEditStore.formItemsCurrentValue || {};
    quickEditStore.setFormItemsCurrentValue({ ...editValues, [this.key]: args[0] }) //更新到快速编辑对象
  }

  onChange = (...args) => {
    let oldvalue = this.getValue();
    this.setSelfValue(...args);
    this.quickEditOnchange(args); //快速编辑字段维护
    let newvalue = this.getValue();
    const that = this;
    setTimeout(() => {
      that.onChangFuncs.map(f => {
        if (_.isFunction(f)) {
          f(...args);
        }
      });
      const onChanges = _.get(window.CubeTrigger.onChangeFuns, that.key);
      if (onChanges && _.isArray(onChanges)) {
        onChanges.map(f => {
          if (_.isFunction(f)) {
            if (oldvalue == newvalue) {//如果值没变化,不触发字段联动
              return;
            }
            const path = that.path;
            if (path.indexOf('detail_') > -1) {
              const paths = path.split('.');
              if (paths.length == 3) {
                f(paths[1]);
              } else {
                f();
              }
            } else {
              f();
            }
          }
        })
      }
      //插入代码快绑定函数触发
      const path = that.path;
      const fieldName = getDomIdByFieldKey(path);
      const funs = modeForm.__propertyChangeFnObj[fieldName];
      if (funs) {
        funs.forEach(fun => {
          if (typeof fun === 'function') {
            fun(document.getElementById(fieldName), fieldName, that.values())
          }
        })
      }
      //明细字段值变化触发事件
      const detailFuns = modeForm.__detailFieldChangeFnObj[that.key];
      if (detailFuns) {
        detailFuns.forEach(fun => {
          if (typeof fun === 'function') {
            const rowIndex = fieldName.split('_')[1];
            fun(fieldName, rowIndex, that.values())
          }
        })
      }
    }, 100);
    /***
     * 这个校验很影响性能，缩短三分之二时间 
     * 批量修改的时候加个第四个参数true，判断下
     */
    if(!args[3]){
      this.validate();
      this.showErrors(true);
    }
    //ecme字段变更时回调
    if (oldvalue == newvalue) {//如果值没变化,不触发回调
      return;
    }
    const path = that.path;
    const fieldName = getDomIdByFieldKey(path);
    //执行力平台组
    if (this.form.card.getFieldProps(path).fieldhtmltype === '6' && args.length === 1 && args[0] === '-1') {
      return false
    } else {
      modeForm.ecmeFieldEventCallBack("onChange", fieldName, "form");
    }
  }

  getDetailTable = (): string => {
    return this.path.split('.')[0];
  }
  getDetailRowIndex = () => {
    let index = _.trim(this.path.replace(this.getDetailTable(), '').replace(this.key, ''), '.');
    if (index && isNumber(index)) {
      return parseInt(index);
    } else {
      return -1;
    }
  }

  onFocus = () => {
    modeForm.triggerFieldAction("onfocus", this.key);
    //ecme字段onFocus时回调
    const path = this.path;
    const fieldName = getDomIdByFieldKey(path);
    modeForm.ecmeFieldEventCallBack("onfocus", fieldName, "form");
  }

  onBlur = () => {
    modeForm.triggerFieldAction("onblur", this.key);
    //ecme字段onBlur时回调
    const path = this.path;
    const fieldName = getDomIdByFieldKey(path);
    modeForm.ecmeFieldEventCallBack("onblur", fieldName, "form");
  }

  //处理多人力操作组信息
  buildMultiUserGroupInfo = (ids = '', datas = []) => {
    const multiUserType = { "subcom": 2, "dept": 3, "group": 4, "virtual_subcom": 5, "virtual_dept": 7, "all": 9 };
    let groupInfo = {};
    let i = 0;
    datas && datas.map((v, k) => {
      const type = v['type'];
      const typeid = v['id'] || 0;
      if (type == "subcom" || type == "dept" || type == "group") {
        let users: any = [];
        users = v['users'];
        let userIds: any = [];
        users && users.map((o) => {
          userIds.push(o['id']);
        });
        groupInfo[`group_${i}`] = multiUserType[type] + "|" + typeid + "|" + userIds.join(",");
        i++;
      } else if (type == "all") {
        groupInfo[`group_${i}`] = multiUserType[type] + "|" + typeid + "|" + ids;
        i++;
      }
    });
    groupInfo['groupnum'] = i;
    return groupInfo;
  }
}

const bindings = {
  default: {
    id: 'id',
    name: 'name',
    value: 'value',
    valueSpan: 'valueSpan',
    valueObj: 'valueObj',
    label: 'label',
    checked: 'checked',
    options: 'options',
    placeholder: 'placeholder',
    disabled: 'disabled',
    onChange: 'onChange',
    onBlur: 'onBlur',
    onFocus: 'onFocus',
    autoFocus: 'autoFocus',
    onError: 'onError',
    isView: 'isView',
    isHide: 'isHide',
    isEdit: 'isEdit',
    isMandatory: 'isMandatory',
    viewAttr: 'viewAttr',
    uploadData: 'uploadData',
    dataParams: 'dataParams',
    browserProps: 'browserProps',
    forceRender: 'forceRender',
    startDate: 'startDate',
    endDate: 'endDate',
  }
};
export const rules = {};
export default class CubeForm extends Form {
  card: CardStore;
  initFields: Function;
  has: (key: string) => boolean;
  $: Function;
  add: Function;
  update: Function;
  values: Function;
  validate: Function;
  isValid: boolean;
  showErrors: Function;
  map: Function;
  isInit: boolean = false;
  errors: Function;
  isDrag: boolean = false;


  constructor(card, ...props) {
    super(...props);
    this.isInit = true;
    this.card = card;
  }

  @action
  updateValues = (values: any, allfields?, isInit?: string) => {
    _.each(values, (value, key) => {


      // const { options = [] } = _.get(allfields, key) || {};
      // if (!value) {
      //     const selecteds = options.filter(o => o.selected);
      //     if (selecteds.length > 0) {
      //         value = _.get(selecteds, '[0].key');
      //     }
      //     if (!value) {
      //         return;
      //     }
      // }

      if (key.startsWith('detail_')) {
        const detailTable = this.$(key);
        _.each(value, (v, index) => {
          if(v['dtl_index']){ index = v['dtl_index'] }
          const row = detailTable.$(`${index}`);
          _.each(v, (v1, k1) => {
            if (!v1) {
              return;
            }
            /**
             * E9建模明细表布局里明细字段不显示的情况下会导致字段的值无法正常显示，
             * 只有第一行显示个别字段，提交后会导致增加行或者行数会翻倍
             */
            if (!row.has(k1)) { return };
            if (_.isString(v1) || _.isNumber(v1)) {
              if (isInit && isInit == "init") {
                row.$(k1).onChangeNoTrigger(v1);
              } else {
                row.$(k1).onChange(v1);
              }
            } else {

              const field = row.$(k1);
              if (isInit && isInit == "init") {
                if (v1.filedatas) { //附件类型
                  this.dealAnnex(field, v1);
                } else {
                  field.onChangeNoTrigger(v1.value, v1.valueSpan, v1.valueObj);
                }
              } else {
                if (v1.filedatas) {
                  this.dealAnnex(field, v1);
                } else {
                  field.onChange(v1.value, v1.valueSpan, v1.valueObj);
                }
              }
            }
          })
        })
      } else {
        if (_.isString(value) || _.isNumber(value)) {
          this.$(key).onChangeNoTrigger(value);
        } else {
          //field1.fieldhtmltype === '5' && _.isNumber(Number(field1.value)) && field1.value
          const field = this.$(key);
          field.onChangeNoTrigger(value.value, value.valueSpan, value.valueObj);
        }
      }
    });

  }

  @action
  initCubeFields = (fields: any) => {
    this.initFields({ fields });
    this.isInit = true;
  }

  makeField(props) {
    return new CubeField(props, this);
  }

  dealAnnex(field, value) { //字段联动处理附件类型字段
    if (value.filedatas) {
      field.uploadData = value;
      if (field.uploadData.filedatas) {
        let v: any = [];
        field.uploadData.filedatas.forEach(item => {
          v.push(item.fileid);
        });
        field.onChange(v.join(','));
      }
    }
  }

  bindings() {
    return bindings;
  }

  plugins() {
    return {
      dvr: {
        package: validatorjs,
        extend: ($validator) => {
          $validator.useLang('zh');
          let messages = $validator.getMessages('zh');
          $validator.setMessages('zh', messages);
          Object.keys(rules).forEach((key) =>
            $validator.register(key, rules[key].function, rules[key].message));
        }
      }
    }
  }

  getDetailInitData = (detail: string) => {
    const datas: any[] = [];
    if (this.has(detail)) {
      const detailTable = this.$(detail);
      detailTable.map((row, index: number) => {
        row.map(f => {
          if ((f.key as string).startsWith('field')) {
            const { fieldhtmltype, fieldtype } = this.card.getFieldProps(f.key);
            if (fieldhtmltype === '3' && (fieldtype != '2' && fieldtype != '19')) {
              _.set(datas, `${index}.${f.key}`, toJS(f.valueObj));
            } else {
              _.set(datas, `${index}.${f.key}`, f.getValue());
              if (fieldhtmltype === '6') {
                _.set(datas, `${index}.${f.key}uploadData`, toJS(f.uploadData));
              }
            }
          } else {
            return _.set(datas, `${index}.${f.key}`, f.getValue());
          }
        });
      });
    }
    return datas;
  }

  /***
   * 这里加个参数，批量修改不走校验，校验比较耗时，影响性能
   */
  @action
  setValue = (key: string, value: any,bool:boolean = false) => {
    if (this.judgeHasKey(key)) {
      return;
    }
    const field = this.$(key);
    const { fieldtype, fielddbtype } = this.card.getFieldProps(field.key);
    if (value.filedatas) {
      field.uploadData = value;
      if (field.uploadData.filedatas) {
        let v: any = [];
        field.uploadData.filedatas.forEach(item => {
          v.push(item.fileid);
        });
        field.onChange(v.join(','),null, [],bool);
      }
    } else if (value == null || value == undefined) {
      field.onChange('', null, [],bool);
    } else if (_.isString(value) || _.isNumber(value)) {
      if (fieldtype == '2') {
        if (value > 2147483647 || value < -2147483648) return;
      } else if (fieldtype == '3' || fieldtype == '4' || fieldtype == '5') {
        if (value > 999999999999.999999999999 || value < -999999999999.999999999999) return;//最大支持到千亿
      } else if (fieldtype === '1') {
        const valLen = InputUtil.realLength(value);
        let fieldlength_tmp = 999;
        if (fielddbtype.indexOf("varchar") > -1) {
          fieldlength_tmp = parseInt(fielddbtype.substring(fielddbtype.indexOf("(") + 1, fielddbtype.length - 1));
        }
        if (fieldlength_tmp && valLen > fieldlength_tmp) {
          message.warning(`"${field.$label}"${getLabel(20246, "文本长度不能超过") + fieldlength_tmp + '(' + getLabel(20247, '1个中文字符等于3个长度') + ')'}`);
          value = InputUtil.checkLength(value, valLen, fieldlength_tmp);
        }
      }
      field.onChange(value,null, [],bool);
    } else if (fieldtype == '141' && _.isArray(value) && _.has(value[0], ("prop"))) {
      let obj = deal4ReplaceDatas(value, fieldtype);
      field.onChange(obj.value, obj.valueSpan, obj.valueObj,bool);
    } else {
      field.onChange(value.map(d => d.id).join(','), value.map(d => d.name || d.lastname).join(','), value,bool);
    }
  }

  @action
  getValue = (key: string) => {
    if (this.judgeHasKey(key)) {
      return '';
    }
    const value = this.$(key).value;
    return value;
  }

  //判断key是否存在
  @action
  judgeHasKey = (key: string) => {
    let arr = key.split('.');
    let istrue = false;
    if (arr.length > 1) {//明细表逐层判断key是否存在
      if (this.has(arr[0]) && this.$(arr[0]).has(arr[1]) && this.$(arr[0]).$(arr[1]).has(arr[2])) {
        istrue = false;
      } else {
        istrue = true;
      }
    } else {//主表
      if (!this.has(arr[0])) {
        istrue = true;
      }
    }
    return istrue;
  }


  @action
  clearAllViewAttr = (key: string, ignore: string[] = [], form: any = this) => {
    form.map(field => {
      if (`${field.key}`.startsWith('field')) {
        if (ignore.indexOf(field.key) > -1) {
          return;
        }
        field.removeViewAttrs(key);
      } else {
        this.clearAllViewAttr(key, ignore, field);
      }
    });
  }
  @action
  initDetailDatas = (datas: any[] = [], detail: string, allfields: any, detailDefaultValue: any, startkey, callback) => {
    if (this.has(detail)) {
      const detailTable = this.$(detail);
      const _datas: any = {};
      const uploadData: any = {};
      datas.map((d: any, key: number) => {
        if (startkey) { key = key + startkey };
        const _d = {};
        _.each(d, (v, k) => {
          if (k.endsWith('uploadData')) {
            const _k = k.replace('uploadData', '');
            const { detail } = this.card.getFieldProps(_k);
            uploadData[`${detail}.${key}.${_k}`] = v;
            return;
          }
          if (v && _.isArray(v)) {
            _.set(_d, k, deal4ReplaceDatas(v, this.card.getFieldProps(k).fieldtype))
          } else {
            _.set(_d, k, v);
          }
        })
        detailTable.add('', { key });
        _.set(_datas, key, _d);
      });
      if (this.has(detail)) {
        const _detailDefaultValue: any = {};
        // 处理明细表 选择框字段在选项维护中设置的默认值
        _.forEach(allfields, (field, key) => {
          if (field.detail===detail&&field.fieldhtmltype==='5'&&field.value) {
            _.set(_detailDefaultValue, key, field.value);
          }
        })
        _.each(detailDefaultValue, (v, k) => {
          if (v && _.isArray(v)) {
            _.set(_detailDefaultValue, k, deal4ReplaceDatas(v, this.card.getFieldProps(k).fieldtype))
          } else {
            _.set(_detailDefaultValue, k, v);
          }
        });
        this.$(detail).detailDefaultValue = _detailDefaultValue;
      }
      this.updateValues({
        [detail]: _datas
      }, allfields, 'init');
      /***明细表初始化完成，回调行列计算 */
      callback && typeof callback == 'function' && callback();

      this.setUploadData(uploadData);
    }
  }

  @action
  setUploadData = (data) => {
    _.each(data, (v, k) => {
      try {
        this.$(k).setUploadData(v);
      } catch (e) {
      }
    })
  }

  get firstErrorField() {
    if (this.isValid) {
      return false;
    } else {
      return $('.cube-check-error').first();
    }
  }



  @action
  addRow = (orderid: string, type?: string) => {
    return verifyCustomRegisterEvent(modeForm.OPER_ADDROW + orderid, () => {
      const fieldname = `detail_${orderid}`;
      const field = this.$(fieldname);
      const fields = field.map(d => parseInt(d.key));

      const maxIndex = fields.length > 0 ? Math.max(...fields) + 1 : 0;
      const key = `${maxIndex ? maxIndex : 0}`;
      field.add('', { key });
      let detailDefaultValue = toJS(field.detailDefaultValue) ||{};
      if(type == '0'){
        detailDefaultValue = {...detailDefaultValue,dtl_id:guid(),dtl_index:key}
      }
      this.updateValues({
        [fieldname]: {
          [key]: detailDefaultValue
        }
      }, this.card.allFields);
      this.card.cubeTrigger.executeWhenAddRow(fieldname, key);
      this.checkPagination(orderid, "add");
      //执行自定义新增行接口，延时解决DOM先变更，函数体取新增行值情况
      modeForm.triggerAction(modeForm.ACTION_ADDROW + orderid, [key], 100);
      /***快速编辑-新增后当前行可编辑 */
      if (type == '0') {
        let detailkeys = _.keys(field.value[0]).filter(d => d.startsWith('field'));
        const detailkeysState = {};
        _.forEach(detailkeys,fieldid=>{
          const { editstate } = this.card.getFieldEditState(fieldid);
          if(editstate== '3'){
            detailkeysState[fieldid] = editstate;
          }
          field.$(key).$(fieldid).setViewAttrs("", editstate== '2' ? '1':(editstate== '3'?'2':'3'));
        });
        const _this = this;
          _this.card.quickEditStore.addDetals(fieldname,key,detailDefaultValue,detailkeysState);
      }
    });


  }
  @action
  copyRow = (orderid: string, type?: string) => {
    const fieldname = `detail_${orderid}`;
    const field = this.$(fieldname);
    const fields = field.map(d => parseInt(d.key));
    const maxIndex = fields.length > 0 ? Math.max(...fields) + 1 : 0;

    const selectedKeys = field.map(d => d).filter(f => f.$('checkbox').values() == '1').map(d => d.key);
    if (selectedKeys.length == 0) {
      Modal.warning({
        title: getLabel(558, '提示'),
        content: <div>{getLabel(31433, '请选择需要复制的数据')}</div>,
      })
    }
    let copyRowDatas: Array<object> = [];
    selectedKeys.map((d, index) => {
      const row = field.$(d);
      const rowValues = row.values() || {};
      const _d = { ...rowValues, dtl_id: '', checkbox: '0' };
      const newRowKey = `${maxIndex + index}`;
      field.add(_d, { key: newRowKey });
      this.card.cubeTrigger.executeWhenCopyRow(fieldname, newRowKey,rowValues);
      const newRow = field.$(newRowKey);
      for (let key in _d) {
        newRow.$(key).value = rowValues[key];
        newRow.$('checkbox').value = '0';
        if(type == '0'){ //快速编辑加个id,方便替换
           newRow.$('dtl_id').value = guid();
        }else{
          newRow.$('dtl_id').value = '';
        }
        const { valueSpan, valueObj } = row.$(key);

        newRow.$(key).valueObj = valueObj;
        newRow.$(key).valueSpan = valueSpan;
      }
      copyRowDatas.push(newRow.value);
    })
    this.checkPagination(orderid, "copy");
    /****
       * 快速编辑--复制的时候直接保存的
      */
    if (type == '0') {
      const _this = this;
      setTimeout(()=>{
        _this.card.quickEditStore.handleDetals('copy',fieldname,copyRowDatas);
      },100)
    }
  }

  @action
  delRow = (orderid: string, type?: string) => {
    return verifyCustomRegisterEvent(modeForm.OPER_DELROW + orderid, () => {
      const fieldname = `detail_${orderid}`;
      const field = this.$(fieldname);
      const values = field.values();
      const delids = _.compact(values.filter(d => d.checkbox == '1').map(d => _.get(d, `dtl_id`)));
      let delDatas:Array<object> = _.compact(values.filter(d => d.checkbox == '1')) || []; //删除的数据,g过滤掉新增未保存的
          delDatas = delDatas.filter(d=>d[`dtl_id`].length < 30);
      const delkeys = field.map(d => d).filter(f => f.$('checkbox').values() == '1').map(d => d.key);
      if (delkeys.length == 0) {
        Modal.warning({
          title: getLabel(558, '提示'),
          content: <div>{getLabel(22686, '请选择需要删除的数据')}</div>,
        });
        return;
      }
      Modal.confirm({
        title: getLabel(82873, '请确认'),
        content:( type == '0'&& delDatas.length >0) ? getLabel('521950','删除后会执行保存,确定删除吗?')  : <div>{getLabel(127574, '确定删除吗？')}</div>,
        onOk: () => {
          this.card.cubeTrigger.executeWhenDelRow(fieldname, delkeys);
          _.each(delkeys, key => field.del(key));

          if (!this.has(`deldtlid${orderid}`)) {
            this.add('', { key: `deldtlid${orderid}` });
          }
          const detialidField = this.$(`deldtlid${orderid}`);
          const oldValue = detialidField.values();
          let newValue: string;
          if (oldValue) {
            if (delids.length > 0) {
              newValue = `${oldValue},${delids.join(',')}`;
            } else {
              newValue = oldValue;
            }
          } else {
            newValue = delids.join(',');
          }
          detialidField.set('value', newValue);
          this.checkPagination(orderid, 'del');
          //执行自定义删除行接口
          modeForm.triggerAction(modeForm.ACTION_DELROW + orderid, [...delkeys], 50);
          /***快速编辑-删除后确认直接保存 */
          if (type == '0') {
            const _this = this;
            setTimeout(()=>{
              if(delDatas.length>0){
                _this.card.quickEditStore.handleDetals('delete',fieldname,delDatas);
              }
              
            },100)
          }
        }
      });
    });


  }
  @action
  delDetailRow = (detailMark: string, rowIndexMark: string) => {
    const orderid = detailMark.split("_")[1];
    const field = this.$(detailMark);
    let delkeys: any = [];
    if (rowIndexMark === "all") {
      delkeys = field.map(d => d.key);
    } else {
      delkeys = rowIndexMark.split(",").map(d => Number(d));
    }
    const fieldname = `detail_${orderid}`;
    const values = this.$(fieldname).values();
    let delids: any = []; //删除的ids
    for (let i = 0; i < delkeys.length; i++) {
      const key = delkeys[i];
      delids.push(_.get(values[key], `dtl_id`));
    }
    delids = _.compact(delids);

    //删除数据
    _.each(delkeys, key => field.del(key));
    //保存被删除的数据
    if (!this.has(`deldtlid${orderid}`)) {
      this.add('', { key: `deldtlid${orderid}` });
    }
    const detialidField = this.$(`deldtlid${orderid}`);
    const oldValue = detialidField.values();
    let newValue: string = "";
    if (oldValue) {
      if (delids.length > 0) {
        newValue = `${oldValue},${delids.join(',')}`;
      } else {
        newValue = oldValue;
      }
    } else {
      newValue = delids.join(',');
    }
    detialidField.set('value', newValue);
    this.checkPagination(orderid, 'del');
  }

  @action
  checkAll = (detail, checked, canNotDeleteHis?) => {
    this.$(detail).map(d => {
      if (canNotDeleteHis) {//不允许删除已有明细
        if (!d.value.dtl_id) {
          d.$('checkbox').set('value', checked ? '1' : '0');
        }
      } else {
        const rowsObj = this.card.detailMap[detail] && this.card.detailMap[detail][`row_${d.key}`];
        const disableCheck = rowsObj ? rowsObj.disableCheck : false;
        if (disableCheck) { return }
        d.$('checkbox').set('value', checked ? '1' : '0');
      }
    });
  }

  @action('重置明细选中情况')
  controlDetailCheck = (detailMark,rowId,isCheck) => {
    let checked = isCheck ? '1' : '0';
    let form = this.$(detailMark);
    rowId = rowId.indexOf('row_')>-1 ? rowId.replace('row_','') : rowId;
    form.map(d => {
        if(d.key == rowId){
            let checkVal = d.$('checkbox').value;
            if(checkVal == '1'){
              d.$('checkbox').set('value', checked);
            }
        }
    });
  }

  @action
  checkPagination = (orderid: string, type = "") => {    //明细表开启分页，页码跳动
    const fieldname = `detail_${orderid}`;
    const field = this.$(fieldname);
    const pageSize = Number(field.pageSize);
    const pageNum = Number(field.pageNum);
    const total = field.values().length;
    const intPage = Math.ceil(total / pageSize);
    switch (type) {
      case 'add':
      case 'copy':
        if (pageSize * pageNum < total && pageSize * (pageNum + 1) > total) {
          field.pageNum = pageNum + 1;
        } else {
          field.pageNum = intPage;
        }
        break;
      case 'del':
        if (intPage <= pageNum) {
          field.pageNum = intPage;
        }
        break;
      default:
        break;
    }
    // if (pageSize * pageNum < total && pageSize * (pageNum+1)>total) {
    //   field.pageNum = pageNum + 1;
    // } else {
    //   for (let i = 0; i < pageNum; i++) {
    //     if (pageSize * i >= total) {
    //       field.pageNum = i;
    //     }
    //   }
    // }
  }

  @action
  setDate = (key: string, start: any = null, end: any = null) => {
    if (this.judgeHasKey(key)) {
      return;
    }
    const field = this.$(key);
    field.startDate = start;
    field.endDate = end;
  }

}
